import store from '@/store'
import storage from '@/utils/storage'
import Config from '@/core/config'

/*#ifdef APP-PLUS*/
const platform="app"
/*#endif*/
/*#ifdef H5*/
const platform="H5"
/*#endif*/
/*#ifdef MP*/
const platform="MP-WEIXIN"
/*#endif*/

var network = process.env.NODE_ENV === 'development' ? '/api' : ''

// #ifdef MP-WEIXIN
	network = Config.get('apiUrl');
// #endif

let isConnected = false
let networkType = 'none'
uni.onNetworkStatusChange((a, b) => {
	isConnected = a
	networkType = b
})
export {
	isConnected,
	networkType
}

function request({
	url,
	method,
	data,
	status
}) {
	return new Promise((resolve, reject) => {
		url = network + url
		const token = storage.get('AccessToken') ? storage.get('AccessToken') : ''
		uni.request({
			url,
			method,
			data,
			header: {
				 'X-AUTH-TOKEN-UID': uni.getStorageSync('token'),
				 'storeId': 'AKIDJO2NRHlb1B3h49uWpsRm10jEWoqb4g7H',
				 'access-token': token,
				 'platform':platform
			},
			success: response => {
				const res = response.data
				if(status){
					resolve(res)
				}
				if (res.status !== 200) {
					if (res.status === 403 || res.status === -1) {
						// 清空登录状态
						store.dispatch('user/reset')
						// 获取当前页面
						const pages = getCurrentPages()
						const current = pages[pages.length - 1]
						let path = '/' + current.route
						const param = current.options || (current.$route ? current.$route.query :
							[])
						for (const key in param) {
							if (path.indexOf('?') === -1) {
								path += `?${key}=${param[key]}`
							} else {
								path += `&${key}=${param[key]}`
							}
						}
						path = encodeURIComponent(path)
						if (current.route.indexOf('pages/user/login/index') === -1) {
							if (config.tabList.some(item => item === current.route === item)) {
								uni.navigateTo({
									url: `/pages/user/login/index?redirect=${path}`
								})
							} else {
								uni.redirectTo({
									url: `/pages/user/login/index?redirect=${path}`
								})
							}
						}
						reject('暂未登录!')
					} else if(res.status === 500){
						resolve(res)
					}else {
						uni.hideLoading()
						uni.showToast({
							title: res.reason || '请求错误,请稍后重试!',
							icon: 'none',
							duration: 3000
						})
						reject(res.reason || '请求错误,请稍后重试!')
					}
				} else {
					resolve(res)
				}
			},
			fail: () => {
				uni.hideLoading()
				if (isConnected) {
					uni.showToast({
						title: '请求超时,请稍后重试!',
						icon: 'none'
					})
					reject('请求超时,请稍后重试!')
				} else {
					uni.showToast({
						title: '当前没有联网,请检查网络后重试!',
						icon: 'none'
					})
					reject('当前没有联网,请检查网络后重试!')
				}
			}
		})
	})
}

export default request
